import shell from "shelljs";
import path from 'path'
import Client from "ssh2-sftp-client";
import ora from "ora";

const config = {
  ip: '43.142.161.237', // ssh地址
  username: 'root', // ssh 用户名
  port: '22', // 端口
  password: 'bzf042800!', // ssh 密码
  path: '/root/web/dist', // 操作开始文件夹 可以直接指向配置好的地址
  rmpath: '/root/web/dist' // 需要删除的文件夹
}

// 打包 npm run build
const compileDist = async () => {
  if (shell.exec(`npm run build`).code === 0) {
    connectSSh()
  }
}

function connectSSh() {
  const loading = ora().start()
  loading.color = "green"
  console.log('开始连接服务器...');
  let sftp = new Client()
  sftp.connect({
    host: config.ip, // 服务器 IP
    port: config.port,
    username: config.username,
    password: config.password
  })
    .then(async () => {
      console.log('删除旧文件')
      await sftp.rmdir(config.rmpath, true)
      console.log('开始更新文件...')
      await sftp.uploadDir(path.resolve('./dist'), config.path)
      console.log('更新完成！')
    })
    .then(() => {
      loading.succeed("上传成功！")
      loading.stop()
      sftp.end()
    }).catch((err) => {
      console.log(err);
      loading.fail("上传失败！")
      loading.stop()
      sftp.end()
    })
}

compileDist()

